package com.im.partchat.ui.fragment.learn;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.im.partchat.App;
import com.im.partchat.R;
import com.im.partchat.adapter.base.XRecyclerViewAdapter;
import com.im.partchat.adapter.learn.NewTab1FragmentAdapter;
import com.im.partchat.base.BaseFragment;
import com.im.partchat.bean.learn.Tab1New;
import com.im.partchat.bean.main.BannerBean;
import com.im.partchat.bean.request.RequestBean;
import com.im.partchat.mvp.persenter.GetNewsPersenter;
import com.im.partchat.utils.GlideImageLoader;
import com.im.partchat.utils.Navigation;
import com.im.partchat.widget.banner.Banner;
import com.im.partchat.widget.banner.BannerConfig;
import com.im.partchat.widget.banner.listener.OnBannerListener;

import org.reactivestreams.Publisher;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * Created by flyou on 2017/6/30.
 * VersionCode: 1
 * Desc:
 */

public class Tab1Fragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, XRecyclerViewAdapter.OnLoadMoreListener {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.reFreshLayout)
    SwipeRefreshLayout reFreshLayout;
    NewTab1FragmentAdapter adapter;
    private View headLayout;
    private Banner banner;
    private GetNewsPersenter getNewsPersenter;
    private int currentPageNo = 1;

    private List<BannerBean> myBannerBeanes = new ArrayList<>();

    private boolean isFirst=true;
    private List<Tab1New> tab1NewList = new ArrayList<>();


    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            myBannerBeanes = (List<BannerBean>) savedInstanceState.get("bannerBean");
        }
        headLayout = LayoutInflater.from(App.getApplication()).inflate(R.layout.view_new_header_layout, null, false);
        banner = (Banner) headLayout.findViewById(R.id.banner);
        banner.setImageLoader(new GlideImageLoader());
        reFreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        reFreshLayout.setOnRefreshListener(this);

        adapter = new NewTab1FragmentAdapter(App.getApplication(), recyclerView, tab1NewList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(App.getApplication(), LinearLayoutManager.VERTICAL, false));

        adapter.setOnLoadMoreListener(this);
        adapter.isLoadMore(true);
        if (myBannerBeanes != null) {
            banner.setBannerBeans(myBannerBeanes);
            banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
            banner.setDelayTime(3000);
            banner.start();

        }
        adapter.addHeaderView(headLayout);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

        outState.putParcelableArrayList("bannerBean", (ArrayList<? extends Parcelable>) myBannerBeanes);
        super.onSaveInstanceState(outState);

    }

    private void initBanner(final List<Tab1New> myTab1NewList) {
        Flowable
                .just(myTab1NewList)
                .flatMap(new Function<List<Tab1New>, Publisher<Tab1New>>() {
                    @Override
                    public Publisher<Tab1New> apply(List<Tab1New> tab1News) throws Exception {
                        return Flowable.fromIterable(tab1News);
                    }
                })
                .map(new Function<Tab1New, BannerBean>() {
                    @Override
                    public BannerBean apply(Tab1New aTab1New) throws Exception {
                        BannerBean bannerBean = new BannerBean(aTab1New.getTitle(), aTab1New.getImg());
                        return bannerBean;
                    }
                })
                .take(5)
                .toList()
                .subscribe(new Consumer<List<BannerBean>>() {
                    @Override
                    public void accept(List<BannerBean> bannerBeanes) throws Exception {
                        myBannerBeanes = bannerBeanes;
                        banner.setBannerBeans(myBannerBeanes);
                        banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
                        banner.setDelayTime(3000);
                        banner.start();
                        banner.setOnBannerListener(new OnBannerListener() {
                            @Override
                            public void OnBannerClick(View view, int position) {
                                Navigation.navigateWebview("新闻详情", myTab1NewList.get(position).getUrl());
                            }
                        });
                        Log.d(TAG, "onLoadDataSuccess: " + Thread.currentThread().getName());

                    }
                });
    }

    private void initAdapter(List<Tab1New> getTab1NewList) {

        Flowable
                .just(getTab1NewList)
                .flatMap(new Function<List<Tab1New>, Publisher<Tab1New>>() {
                    @Override
                    public Publisher<Tab1New> apply(List<Tab1New> tab1News) throws Exception {
                        return Flowable.fromIterable(tab1News);
                    }
                })
                .skip(5)
                .toList()
                .subscribe(new Consumer<List<Tab1New>>() {
                    @Override
                    public void accept(List<Tab1New> tab1News) throws Exception {
                        adapter.clear();
                        adapter.addAll(tab1News);

                    }
                });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_learn_list;
    }

    @Override
    protected void initData() {
        getNewsPersenter = new GetNewsPersenter(this, this);
        getNewsPersenter.getNewList(RequestBean.COLUMN_XWDT, 1);

    }

    @Override
    public void onLoadDataSuccess(Object o, String flag) {
        if (isFirst) {
            onRefresh();
            isFirst=false;
        }
        List<Tab1New> myTab1NewList;
        Gson gson = new Gson();
        String json = gson.toJson(o);
        Type type = new TypeToken<List<Tab1New>>() {}.getType();
        myTab1NewList = gson.fromJson(json.toString(),type);
        Log.d(TAG, "onLoadDataSuccess: " + Thread.currentThread().getName());

        if (myTab1NewList != null && myTab1NewList.size() == 10){
            adapter.isLoadMore(true);
        }else {
            adapter.showLoadComplete();
        }

        if (currentPageNo == 1) {
            if (myTab1NewList == null || myTab1NewList.size() == 0) {
                showEmpty();
                return;
            }


            initBanner(myTab1NewList);
            initAdapter(myTab1NewList);

        } else {
            if (myTab1NewList == null || myTab1NewList.size() == 0) {
                adapter.showLoadComplete();
                return;
            }
            if (myTab1NewList.size()<10){
                adapter.showLoadComplete();
            }
            adapter.addAll(myTab1NewList);
        }
    }

    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {
        reFreshLayout.setRefreshing(false);
    }


    @Override
    public void onRefresh() {
        currentPageNo = 1;
        getNewsPersenter.getNewList(RequestBean.COLUMN_XWDT, 1);
    }



    @Override
    public void onRetry() {
        getNewsPersenter.getNewList(RequestBean.COLUMN_XWDT, currentPageNo);
    }

    @Override
    public void onLoadMore() {
        currentPageNo++;
        getNewsPersenter.getNewList(RequestBean.COLUMN_XWDT, currentPageNo);
    }
}
